<template>
  <div class="" v-loading="loading">
    <el-form
      :model="form"
      ref="formRefDuty"
      :inline="true"
      :rules="rules"
      label-width="20px"
      :disabled="parentType == 'view'"
    >
      <el-table
        :data="form.tableData"
        border
        style="width: 100%; margin-top: 10px"
        default-expand-all
      >
        <el-table-column type="expand">
          <template #default="props">
            <div style="margin-left: 0">
              <subTable
                ref="subTableRef"
                v-model="props.row.planGroupMemberList"
                :parentType="parentType"
                :isShowProdHours="isShowProdHours"
                :prodHoursOriginal="prodHoursOriginal"
                @addUser="handleUserSelectAdd(props, $event)"
              ></subTable>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="工艺段" prop="sectionName" />
        <el-table-column label="班组" prop="workGroupCode">
          <template #default="scope">
            <el-form-item
              label=" "
              :prop="'tableData.' + scope.$index + '.workGroupCode'"
              :rules="{
                required: true,
                message: '班组不能为空',
                trigger: ['blur', 'change'],
              }"
            >
              <el-select
                v-model="scope.row.workGroupCode"
                placeholder="请选择班组"
                clearable
                filterable
                :disabled="parentType == 'view' || parentType == 'update'"
                @change="handleItemChange(scope.row, scope.$index)"
                style="width: 300px"
                @input="$forceUpdate()"
              >
                <el-option
                  v-for="(item, index) in scope.row.planGroupList"
                  :key="index"
                  :label="item.workGroupName"
                  :value="item.workGroup"
                ></el-option>
              </el-select>
            </el-form-item>
            <!-- <el-select
              v-model="scope.row.workGroupCode"
              placeholder="请选择班组"
              clearable
              filterable
              :disabled="parentType == 'view' || parentType == 'update'"
              @change="handleItemChange(scope.row, scope.$index)"
            >
              <el-option
                v-for="(item, index) in scope.row.planGroupList"
                :key="index"
                :label="item.workGroupName"
                :value="item.workGroup"
              >
              </el-option>
            </el-select> -->
          </template>
        </el-table-column>
      </el-table>
    </el-form>
    <UserSelect
      ref="userSelect"
      :showInput="false"
      placeholder="请选择岗位人员"
      :multiple="true"
      title="选择岗位人员"
      @submits="handleUserSelectChange"
    ></UserSelect>
  </div>
</template>

<script setup name="Data">
import { toRefs } from "vue";
import subTable from "./subTable.vue";
import { ref, reactive, watch } from "vue";
// const { proxy } = getCurrentInstance();
const loading = ref(false);
const itemsPersonRowObj = ref({});
const userSelect = ref("userSelect");
const subTableRef = ref();
const prodChangeShiftsMemberList = defineModel();
const props = defineProps([
  "datas",
  "parentType",
  "isShowProdHours",
  "defaultWorkGroup",
  "prodHoursOriginal",
]);
const { parentType, isShowProdHours, defaultWorkGroup, prodHoursOriginal } = toRefs(props);
const data = reactive({
  form: {
    tableData: prodChangeShiftsMemberList,
  },
  rules: {},
});
const { form, rules } = toRefs(data);

// 这两个watch监听是为了实现-生产日期、班次、生产订单二次选择后，默认班组同步更新
watch(
  () => defaultWorkGroup.value,
  (newValue) => {
    if (newValue) {
      // console.log("fghjk", newValue);
      defaultData();
    }
  },
  {
    immediate: true,
    deep: true,
  }
);
watch(
  () => form.value.tableData,
  (newValue) => {
    if (newValue) {
      defaultData();
    }
  },
  {
    immediate: true,
  }
);

function defaultData() {
  for (let i in form.value.tableData) {
    let ele = form.value.tableData[i];
    for (let j in ele.planGroupList) {
      // 前提是选择多条工艺段的时候，且选择多条不同的生产订单时需要遍历多条使获取对应默认班组
      let _defaultWorkGroup = defaultWorkGroup.value?.split(",") || [];
      for (let k in _defaultWorkGroup) {
        if (ele.planGroupList[j].workGroup == _defaultWorkGroup[k]) {
          // console.log("sasasa===========", ele.workGroupCode);
          // if (!ele.workGroupCode) {
          // console.log("why");
          ele.workGroupCode = _defaultWorkGroup[k];
          ele.planGroupMemberList = ele.planGroupList[j].planGroupMemberList;
          // } else {

          // }
        }
      }
    }
  }
}

function handleUserSelectAdd(props, { row, index }) {
  itemsPersonRowObj.value = {
    props: props.row,
    row,
    index,
  };
  userSelect.value.handlePicker();
}

function handleUserSelectChange(val) {
  if (val.name.split(",").length) {
    const params = val.name.split(",").map((el, index) => {
      return {
        nickName: el,
        userId: val.id.split(",")[index],
        workStationId: form.value.workStationCode,
      };
    });
    for (let i in form.value.tableData) {
      let _ele = form.value.tableData[i];
      if (_ele.sectionCode == itemsPersonRowObj.value.props.sectionCode) {
        for (let j in _ele.planGroupList) {
          if (_ele.planGroupList[j].workGroup == itemsPersonRowObj.value.props.workGroupCode) {
            _ele.planGroupMemberList.splice(
              itemsPersonRowObj.value.index,
              0,
              ...params.map((item) => {
                return {
                  workStationName: itemsPersonRowObj.value.row.workStationName,
                  workStationCode: itemsPersonRowObj.value.row.workStationCode,
                  workStationStaffName: item.nickName,
                  workStationStaff: item.userId,
                  prodHoursOriginal: prodHoursOriginal.value,
                };
              })
            );
          }
        }
      }
    }
  }
  // 新增岗位人员后需要监听岗位人员table列表的变化，重新计算生产工时变化并且赋值
  subTableRef.value.watchTableData();
}

function handleItemChange(row, index) {
  form.value.tableData[index].planGroupMemberList =
    row.planGroupList.find((item) => {
      return row.workGroupCode == item.workGroup;
    })?.planGroupMemberList || [];
}
defaultData();
defineExpose({ form });
</script>
<style lang="scss" scoped>
::v-deep .el-dropdown {
  margin-top: 3px !important;
}
</style>
